package com.violet.mq;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.violet.config.RabbitmqConfig;
import com.violet.domain.emuns.ResultCode;
import com.violet.domain.result.StatisticalData;
import com.violet.domain.result.Result;
import com.violet.socket.OrderMessageSocket;
import com.violet.utils.StatisticsUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;


// 监听订单完成消息【确认收获】
@Component
@RequiredArgsConstructor
public class CompletedMonitor {

    private final StatisticsUtils statisticsUtils;

    private final OrderMessageSocket socket;
    private final ObjectMapper objectMapper;

    /**
     * 收到确认收获时，重新统计一遍今日数据
     * @param message 消息
     */
    @RabbitListener(queues = RabbitmqConfig.QUEUE_COMPLETED)
    public void monitor(Message message) throws InterruptedException, JsonProcessingException {
        // 防止订单状态未改变，先执行
        Thread.sleep(1000);
        // 发送消息到前端
        Result<StatisticalData> result = new Result<StatisticalData>()
            .setCode(ResultCode.ORDER_COMPLETED.code)
            .setData(statisticsUtils.generate());
        // 发送消息
        String string = objectMapper.writeValueAsString(result);
        socket.sendMessage(string);
    }


}
